{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/gee-community/geemap/blob/master/docs/workshops/SatMOC_2024.ipynb)\n",
    "\n",
    "**From Satellites to Solutions: Drought Monitoring with Google Earth Engine**\n",
    "\n",
    "-   Registration: <https://www.nesdis.noaa.gov/events/satellites-solutions-drought-monitoring-google-earth-engine>\n",
    "-   Notebook: <https://geemap.org/workshops/SatMOC_2024>\n",
    "-   Earth Engine: <https://earthengine.google.com>\n",
    "-   Geemap: <https://geemap.org>\n",
    "\n",
    "## Introduction\n",
    "\n",
    "This notebook is designed for the summer short course offered by the American Meteorological Society (AMS) Committee on Satellite Meteorology, Oceanography, and Climatology (SatMOC).  \n",
    "\n",
    "### Description\n",
    "\n",
    "Droughts pose a critical threat to water resources, agriculture, and ecosystems worldwide. This hands-on short course will teach you how to harness the power of Google Earth Engine (GEE) to monitor and analyze drought patterns. GEE's vast repository of satellite data and powerful cloud computing capabilities will streamline your drought research and decision-making.\n",
    "\n",
    "In this short course, you will:\n",
    "\n",
    "* Explore the fundamentals of remote sensing for drought monitoring.\n",
    "* Learn to calculate and interpret key drought indices such as the Palmer Drought Severity Index (PDSI) and Standardized Precipitation Index (SPI). \n",
    "* Master GEE coding techniques to process large geospatial datasets.\n",
    "* Create dynamic visualizations that track the evolution of drought conditions over time.\n",
    "* Develop tools to support local and regional drought management strategies.\n",
    "\n",
    "### Prerequisites\n",
    "\n",
    "-   To use geemap and the Earth Engine Python API, you must [register](https://code.earthengine.google.com/register) for an Earth Engine account and follow the instructions [here](https://docs.google.com/document/d/1ZGSmrNm6_baqd8CHt33kIBWOlvkh-HLr46bODgJN1h0/edit?usp=sharing) to create a Cloud Project. Earth Engine is free for [noncommercial and research use](https://earthengine.google.com/noncommercial). To test whether you can use authenticate the Earth Engine Python API, please run [this notebook](https://colab.research.google.com/github/gee-community/geemap/blob/master/docs/notebooks/geemap_colab.ipynb) on Google Colab.\n",
    "\n",
    "-   It is recommended that attendees have a basic understanding of Python and Jupyter Notebook.\n",
    "-   Familiarity with the Earth Engine JavaScript API is not required but will be helpful.\n",
    "-   Attendees can use Google Colab to follow this short course without installing anything on their computer.\n",
    "\n",
    "By the end of this short course, you will have the skills and resources to confidently integrate Google Earth Engine into your drought monitoring and decision-making workflows.\n",
    "\n",
    "### Agenda\n",
    "\n",
    "This short course consists of six 30-minute sessions. During each hands-on session, the attendees will walk through Jupyter notebook examples on Google Colab. At the end of each session, they will complete a hands-on exercise to apply the knowledge they have learned in each session.\n",
    "\n",
    "- Course introduction and software setup (30 mins)\n",
    "    - Introduction and location of short course materials\n",
    "    - Introduction to Earth Engine and geemap \n",
    "    - Google Colab and Earth Engine Python API authentication\n",
    "- Using Earth Engine data (30 mins)\n",
    "    - Earth Engine data types\n",
    "    - Earth Engine Data Catalog\n",
    "    - Exercise: creating cloud-free imagery\n",
    "- Visualizing Earth Engine data (30 mins)\n",
    "    - Geemap Inspector tool, plotting tool, interactive GUI for data visualization\n",
    "    - Legends, color bars, and labels\n",
    "    - Split-panel map and linked maps\n",
    "    - Timeseries inspector and time slider\n",
    "    - Exercise: visualizing timeseries precipitation and vegetation data\n",
    "- Creating timelapse animations (30 mins)\n",
    "    - MODIS vegetation indices\n",
    "    - MODIS temperature data\n",
    "    - GOES satellite data \n",
    "    - Exercise: creating timelapse animations\n",
    "- Drought monitoring (30 mins)\n",
    "    - Exploring drought datasets\n",
    "    - Creating drought timeseries animations\n",
    "    - Computing zonal statistics\n",
    "    - Creating interactive charts\n",
    "    - Exercise: visualizing drought data for a selected region\n",
    "- Analyzing and visualizing precipitation data (30 mins)\n",
    "    - Exploring precipitation datasets\n",
    "    - Creating precipitation timeseries\n",
    "    - Calculating Standardized Precipitation Index (SPI)\n",
    "    - Exercise: calculating SPI for a selected region\n",
    "\n",
    "## Introduction to Earth Engine and geemap\n",
    "\n",
    "Earth Engine is free for [noncommercial and research use](https://earthengine.google.com/noncommercial). For more than a decade, Earth Engine has enabled planetary-scale Earth data science and analysis by nonprofit organizations, research scientists, and other impact users.\n",
    "\n",
    "With the launch of Earth Engine for [commercial use](https://earthengine.google.com/commercial), commercial customers will be charged for Earth Engine services. However, Earth Engine will remain free of charge for noncommercial use and research projects. Nonprofit organizations, academic institutions, educators, news media, Indigenous governments, and government researchers are eligible to use Earth Engine free of charge, just as they have done for over a decade.\n",
    "\n",
    "The geemap Python package is built upon the Earth Engine Python API and open-source mapping libraries. It allows Earth Engine users to interactively manipulate, analyze, and visualize geospatial big data in a Jupyter environment. Since its creation in April 2020, geemap has received over 3,300 GitHub stars and is being used by over 2,700 projects on GitHub.\n",
    "\n",
    "## Google Colab and Earth Engine Python API authentication\n",
    "\n",
    "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/gee-community/geemap/blob/master/docs/workshops/SatMOC_2024.ipynb)\n",
    "\n",
    "### Change Colab dark theme\n",
    "\n",
    "Currently, ipywidgets does not work well with Colab dark theme. Some of the geemap widgets may not display properly in Colab dark theme.It is recommended that you change Colab to the light theme.\n",
    "\n",
    "![](https://i.imgur.com/EJ0GDP8.png)\n",
    "\n",
    "\n",
    "### Install geemap\n",
    "\n",
    "The geemap package is pre-installed in Google Colab and is updated to the latest minor or major release every few weeks. Some optional dependencies of geemap being used by this notebook are not pre-installed in Colab. Uncomment the following code block to install geemap and some optional dependencies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install -U \"geemap[workshop]\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "Note that some geemap features may not work properly in the Google Colab environmennt. If you are familiar with [Anaconda](https://www.anaconda.com/download) or [Miniconda](https://docs.anaconda.com/free/miniconda), it is recommended to create a new conda environment to install geemap and its optional dependencies on your local computer. \n",
    "\n",
    "```bash\n",
    "conda create -n gee python=3.11\n",
    "conda activate gee\n",
    "conda install -c conda-forge mamba\n",
    "mamba install -c conda-forge geemap pygis\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3",
   "metadata": {},
   "source": [
    "### Import libraries\n",
    "\n",
    "Import the earthengine-api and geemap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ee\n",
    "import geemap"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5",
   "metadata": {},
   "source": [
    "### Authenticate and initialize Earth Engine\n",
    "\n",
    "You will need to create a [Google Cloud Project](https://console.cloud.google.com/projectcreate) and enable the [Earth Engine API](https://console.cloud.google.com/apis/api/earthengine.googleapis.com) for the project. You can find detailed instructions [here](https://book.geemap.org/chapters/01_introduction.html#earth-engine-authentication)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "ee.Authenticate()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "ee.Initialize(project=\"YOUR-PROJECT-ID\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## Creating interactive maps\n",
    "\n",
    "Let's create an interactive map using the `ipyleaflet` plotting backend. The [`geemap.Map`](https://geemap.org/geemap/#geemap.geemap.m) class inherits the [`ipyleaflet.Map`](https://ipyleaflet.readthedocs.io/en/latest/map_and_basemaps/map.html) class. Therefore, you can use the same syntax to create an interactive map as you would with `ipyleaflet.Map`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "To display it in a Jupyter notebook, simply ask for the object representation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "To customize the map, you can specify various keyword arguments, such as `center` ([lat, lon]), `zoom`, `width`, and `height`. The default `width` is `100%`, which takes up the entire cell width of the Jupyter notebook. The `height` argument accepts a number or a string. If a number is provided, it represents the height of the map in pixels. If a string is provided, the string must be in the format of a number followed by `px`, e.g., `600px`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4, height=\"600xp\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "To hide a control, set `control_name` to `False`, e.g., `draw_ctrl=False`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(data_ctrl=False, toolbar_ctrl=False, draw_ctrl=False)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16",
   "metadata": {},
   "source": [
    "### Adding basemaps\n",
    "\n",
    "There are several ways to add basemaps to a map. You can specify the basemap to use in the `basemap` keyword argument when creating the map. Alternatively, you can add basemap layers to the map using the `add_basemap` method. Geemap has hundreds of built-in basemaps available that can be easily added to the map with only one line of code.\n",
    "\n",
    "Create a map by specifying the basemap to use as follows. For example, the `Esri.WorldImagery` basemap represents the Esri world imagery basemap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(basemap=\"Esri.WorldImagery\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18",
   "metadata": {},
   "source": [
    "You can add as many basemaps as you like to the map. For example, the following code adds the `OpenTopoMap` basemap to the map above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_basemap(\"OpenTopoMap\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20",
   "metadata": {},
   "source": [
    "You can also change basemaps interactively using the basemap GUI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "m.add(\"basemap_selector\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22",
   "metadata": {},
   "source": [
    "## Using Earth Engine data\n",
    "\n",
    "### Earth Engine data types\n",
    "\n",
    "Earth Engine objects are server-side objects rather than client-side objects, which means that they are not stored locally on your computer. Similar to video streaming services (e.g., YouTube, Netflix, and Hulu), which store videos/movies on their servers, Earth Engine data are stored on the Earth Engine servers. We can stream geospatial data from Earth Engine on-the-fly without having to download the data just like we can watch videos from streaming services using a web browser without having to download the entire video to your computer.\n",
    "\n",
    "-   **Image**: the fundamental raster data type in Earth Engine.\n",
    "-   **ImageCollection**: a stack or time-series of images.\n",
    "-   **Geometry**: the fundamental vector data type in Earth Engine.\n",
    "-   **Feature**: a Geometry with attributes.\n",
    "-   **FeatureCollection**: a set of features.\n",
    "\n",
    "### Image\n",
    "\n",
    "Raster data in Earth Engine are represented as **Image** objects. Images are composed of one or more bands and each band has its own name, data type, scale, mask and projection. Each image has metadata stored as a set of properties.\n",
    "\n",
    "#### Loading Earth Engine images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23",
   "metadata": {},
   "outputs": [],
   "source": [
    "image = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "image"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24",
   "metadata": {},
   "source": [
    "#### Visualizing Earth Engine images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[21.79, 70.87], zoom=3)\n",
    "image = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 6000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],  # 'terrain'\n",
    "}\n",
    "m.add_layer(image, vis_params, \"SRTM\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26",
   "metadata": {},
   "source": [
    "### ImageCollection\n",
    "\n",
    "An `ImageCollection` is a stack or sequence of images. An `ImageCollection` can be loaded by passing an Earth Engine asset ID into the `ImageCollection` constructor. You can find `ImageCollection` IDs in the [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets).\n",
    "\n",
    "#### Loading image collections\n",
    "\n",
    "For example, to load the image collection of the [Sentinel-2 surface reflectance](https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27",
   "metadata": {},
   "outputs": [],
   "source": [
    "collection = ee.ImageCollection(\"COPERNICUS/S2_SR\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28",
   "metadata": {},
   "source": [
    "#### Visualizing image collections\n",
    "\n",
    "To visualize an Earth Engine **ImageCollection**, we need to convert an **ImageCollection** to an **Image** by compositing all the images in the collection to a single image representing, for example, the min, max, median, mean or standard deviation of the images. For example, to create a median value image from a collection, use the `collection.median()` method. Let's create a median image from the Sentinel-2 surface reflectance collection:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "collection = (\n",
    "    ee.ImageCollection(\"COPERNICUS/S2_SR\")\n",
    "    .filterDate(\"2023-01-01\", \"2024-01-01\")\n",
    "    .filter(ee.Filter.lt(\"CLOUDY_PIXEL_PERCENTAGE\", 5))\n",
    ")\n",
    "image = collection.median()\n",
    "\n",
    "vis = {\n",
    "    \"min\": 0.0,\n",
    "    \"max\": 3000,\n",
    "    \"bands\": [\"B4\", \"B3\", \"B2\"],\n",
    "}\n",
    "\n",
    "m.set_center(-77.0054, 38.8974, 13)\n",
    "m.add_layer(image, vis, \"Sentinel-2\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30",
   "metadata": {},
   "source": [
    "### FeatureCollection\n",
    "\n",
    "A **FeatureCollection** is a collection of Features. A FeatureCollection is analogous to a GeoJSON FeatureCollection object, i.e., a collection of features with associated properties/attributes. Data contained in a shapefile can be represented as a FeatureCollection.\n",
    "\n",
    "#### Loading feature collections\n",
    "\n",
    "The [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets) hosts a variety of vector datasets (e.g,, US Census data, country boundaries, and more) as feature collections. You can find feature collection IDs by searching the data catalog. For example, to load the [TIGER roads data](https://developers.google.com/earth-engine/datasets/catalog/TIGER_2016_Roads) by the U.S. Census Bureau:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "fc = ee.FeatureCollection(\"TIGER/2016/Roads\")\n",
    "m.set_center(-73.9596, 40.7688, 12)\n",
    "m.add_layer(fc, {}, \"Census roads\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32",
   "metadata": {},
   "source": [
    "#### Filtering feature collections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "fc = states.filter(ee.Filter.eq(\"NAME\", \"Tennessee\"))\n",
    "m.add_layer(fc, {}, \"Tennessee\")\n",
    "m.center_object(fc, 7)\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "fc = states.filter(ee.Filter.inList(\"NAME\", [\"California\", \"Oregon\", \"Washington\"]))\n",
    "m.add_layer(fc, {}, \"West Coast\")\n",
    "m.center_object(fc, 5)\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35",
   "metadata": {},
   "outputs": [],
   "source": [
    "region = m.user_roi\n",
    "if region is None:\n",
    "    region = ee.Geometry.BBox(-88.40, 29.88, -77.90, 35.39)\n",
    "\n",
    "fc = ee.FeatureCollection(\"TIGER/2018/States\").filterBounds(region)\n",
    "m.add_layer(fc, {}, \"Southeastern U.S.\")\n",
    "m.center_object(fc, 6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36",
   "metadata": {},
   "source": [
    "#### Visualizing feature collections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "m.add_layer(states, {}, \"US States\")\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "style = {\"color\": \"0000ffff\", \"width\": 2, \"lineType\": \"solid\", \"fillColor\": \"FF000080\"}\n",
    "m.add_layer(states.style(**style), {}, \"US States\")\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "vis_params = {\n",
    "    \"color\": \"000000\",\n",
    "    \"colorOpacity\": 1,\n",
    "    \"pointSize\": 3,\n",
    "    \"pointShape\": \"circle\",\n",
    "    \"width\": 2,\n",
    "    \"lineType\": \"solid\",\n",
    "    \"fillColorOpacity\": 0.66,\n",
    "}\n",
    "palette = [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"]\n",
    "m.add_styled_vector(\n",
    "    states, column=\"NAME\", palette=palette, layer_name=\"Styled vector\", **vis_params\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40",
   "metadata": {},
   "source": [
    "### Earth Engine Data Catalog\n",
    "\n",
    "The [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets) hosts a variety of geospatial datasets. As of July 2024, the catalog contains over [1,100 datasets](https://github.com/opengeos/Earth-Engine-Catalog/blob/master/gee_catalog.tsv) with a total size of over 100 petabytes. Some notable datasets include: Landsat, Sentinel, MODIS, NAIP, etc. For a complete list of datasets in CSV or JSON formats, see the [Earth Engine Datasets List](https://github.com/giswqs/Earth-Engine-Catalog/blob/master/gee_catalog.tsv).\n",
    "\n",
    "#### Searching for datasets\n",
    "\n",
    "The [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets/catalog) is searchable. You can search datasets by name, keyword, or tag. For example, enter \"elevation\" in the search box will filter the catalog to show only datasets containing \"elevation\" in their name, description, or tags. 52 datasets are returned for this search query. Scroll down the list to find the [NASA SRTM Digital Elevation 30m](https://developers.google.com/earth-engine/datasets/catalog/USGS_SRTMGL1_003#description) dataset. On each dataset page, you can find the following information, including Dataset Availability, Dataset Provider, Earth Engine Snippet, Tags, Description, Code Example, and more. One important piece of information is the Image/ImageCollection/FeatureCollection ID of each dataset, which is essential for accessing the dataset through the Earth Engine JavaScript or Python APIs.\n",
    "\n",
    "![](https://i.imgur.com/B3rf4QN.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "m.add_layer(dem, vis_params, \"SRTM DEM\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43",
   "metadata": {},
   "source": [
    "### Exercise 1 - Creating cloud-free imagery\n",
    "\n",
    "Create a cloud-free imagery of a selected US state for the year of 2023. You can use either Landsat 9 or Sentinel-2 imagery. Relevant Earth Engine assets:\n",
    "\n",
    "-   [ee.FeatureCollection(\"TIGER/2018/States\")](https://developers.google.com/earth-engine/datasets/catalog/TIGER_2018_States)\n",
    "-   [ee.ImageCollection(\"COPERNICUS/S2_SR\")](https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR)\n",
    "-   [ee.ImageCollection(\"LANDSAT/LC09/C02/T1_L2\")](https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2)\n",
    "\n",
    "A sample map of cloud-free imagery for the state of Texas is shown below:\n",
    "\n",
    "![](https://i.imgur.com/i3IT0lF.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Type your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45",
   "metadata": {},
   "source": [
    "## Visualizing Earth Engine data\n",
    "\n",
    "### Using the inspector tool\n",
    "\n",
    "Inspect pixel values and vector features using the inspector tool. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=(40, -100), zoom=4)\n",
    "\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\").select(\n",
    "    [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B7\"]\n",
    ")\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "m.add_layer(dem, vis_params, \"SRTM DEM\")\n",
    "m.add_layer(\n",
    "    landsat7,\n",
    "    {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 20, \"max\": 200, \"gamma\": 2.0},\n",
    "    \"Landsat 7\",\n",
    ")\n",
    "m.add_layer(states, {}, \"US States\")\n",
    "m.add(\"inspector\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47",
   "metadata": {},
   "source": [
    "### Using the plotting tool\n",
    "\n",
    "Plot spectral profiles of pixels using the plotting tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\").select(\n",
    "    [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B7\"]\n",
    ")\n",
    "\n",
    "landsat_vis = {\"bands\": [\"B4\", \"B3\", \"B2\"], \"gamma\": 1.4}\n",
    "m.add_layer(landsat7, landsat_vis, \"Landsat\")\n",
    "\n",
    "hyperion = ee.ImageCollection(\"EO1/HYPERION\").filter(\n",
    "    ee.Filter.date(\"2016-01-01\", \"2017-03-01\")\n",
    ")\n",
    "\n",
    "hyperion_vis = {\n",
    "    \"min\": 1000.0,\n",
    "    \"max\": 14000.0,\n",
    "    \"gamma\": 2.5,\n",
    "}\n",
    "m.add_layer(hyperion, hyperion_vis, \"Hyperion\")\n",
    "m.add_plot_gui()\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49",
   "metadata": {},
   "source": [
    "Set plotting options for Landsat."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.set_plot_options(add_marker_cluster=True, overlay=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51",
   "metadata": {},
   "source": [
    "Set plotting options for Hyperion."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.set_plot_options(add_marker_cluster=True, plot_type=\"bar\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53",
   "metadata": {},
   "source": [
    "### Legends, color bars, and labels\n",
    "\n",
    "#### Built-in legends"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54",
   "metadata": {},
   "outputs": [],
   "source": [
    "from geemap.legends import builtin_legends"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55",
   "metadata": {},
   "outputs": [],
   "source": [
    "for legend in builtin_legends:\n",
    "    print(legend)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56",
   "metadata": {},
   "source": [
    "Add NLCD WMS layer and legend to the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "m.add_basemap(\"Esri.WorldImagery\")\n",
    "m.add_basemap(\"NLCD 2021 CONUS Land Cover\")\n",
    "m.add_legend(\n",
    "    title=\"NLCD Land Cover Type\",\n",
    "    builtin_legend=\"NLCD\",\n",
    "    max_width=\"100px\",\n",
    "    height=\"455px\",\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58",
   "metadata": {},
   "source": [
    "Add NLCD Earth Engine layer and legend to the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "m.add_basemap(\"Esri.WorldImagery\")\n",
    "\n",
    "nlcd = ee.Image(\"USGS/NLCD_RELEASES/2021_REL/NLCD/2021\")\n",
    "landcover = nlcd.select(\"landcover\")\n",
    "\n",
    "m.add_layer(landcover, {}, \"NLCD Land Cover 2021\")\n",
    "m.add_legend(title=\"NLCD Land Cover Type\", builtin_legend=\"NLCD\", height=\"455px\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60",
   "metadata": {},
   "source": [
    "#### Custom legends"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61",
   "metadata": {},
   "source": [
    "Add a custom legend by specifying a dictionary of colors and labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "m.add_basemap(\"Esri.WorldImagery\")\n",
    "\n",
    "legend_dict = {\n",
    "    \"11 Open Water\": \"466b9f\",\n",
    "    \"12 Perennial Ice/Snow\": \"d1def8\",\n",
    "    \"21 Developed, Open Space\": \"dec5c5\",\n",
    "    \"22 Developed, Low Intensity\": \"d99282\",\n",
    "    \"23 Developed, Medium Intensity\": \"eb0000\",\n",
    "    \"24 Developed High Intensity\": \"ab0000\",\n",
    "    \"31 Barren Land (Rock/Sand/Clay)\": \"b3ac9f\",\n",
    "    \"41 Deciduous Forest\": \"68ab5f\",\n",
    "    \"42 Evergreen Forest\": \"1c5f2c\",\n",
    "    \"43 Mixed Forest\": \"b5c58f\",\n",
    "    \"51 Dwarf Scrub\": \"af963c\",\n",
    "    \"52 Shrub/Scrub\": \"ccb879\",\n",
    "    \"71 Grassland/Herbaceous\": \"dfdfc2\",\n",
    "    \"72 Sedge/Herbaceous\": \"d1d182\",\n",
    "    \"73 Lichens\": \"a3cc51\",\n",
    "    \"74 Moss\": \"82ba9e\",\n",
    "    \"81 Pasture/Hay\": \"dcd939\",\n",
    "    \"82 Cultivated Crops\": \"ab6c28\",\n",
    "    \"90 Woody Wetlands\": \"b8d9eb\",\n",
    "    \"95 Emergent Herbaceous Wetlands\": \"6c9fb8\",\n",
    "}\n",
    "\n",
    "nlcd = ee.Image(\"USGS/NLCD_RELEASES/2021_REL/NLCD/2021\")\n",
    "landcover = nlcd.select(\"landcover\")\n",
    "\n",
    "m.add_layer(landcover, {}, \"NLCD Land Cover 2021\")\n",
    "m.add_legend(title=\"NLCD Land Cover Type\", legend_dict=legend_dict)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63",
   "metadata": {},
   "source": [
    "#### Creating color bars\n",
    "\n",
    "Add a horizontal color bar."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "m.add_layer(dem, vis_params, \"SRTM DEM\")\n",
    "m.add_colorbar(vis_params, label=\"Elevation (m)\", layer_name=\"SRTM DEM\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65",
   "metadata": {},
   "source": [
    "Add a vertical color bar."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_colorbar(\n",
    "    vis_params,\n",
    "    label=\"Elevation (m)\",\n",
    "    layer_name=\"SRTM DEM\",\n",
    "    orientation=\"vertical\",\n",
    "    max_width=\"100px\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67",
   "metadata": {},
   "source": [
    "Make the color bar background transparent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_colorbar(\n",
    "    vis_params,\n",
    "    label=\"Elevation (m)\",\n",
    "    layer_name=\"SRTM DEM\",\n",
    "    orientation=\"vertical\",\n",
    "    max_width=\"100px\",\n",
    "    transparent_bg=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69",
   "metadata": {},
   "source": [
    "### Split-panel map and linked maps\n",
    "\n",
    "### Split-panel maps\n",
    "\n",
    "Create a split map with basemaps. Note that ipyleaflet has a bug with the SplitControl. You can't pan the map, which should be resolved in the next ipyleaflet release."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "m.split_map(left_layer=\"Esri.WorldTopoMap\", right_layer=\"OpenTopoMap\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71",
   "metadata": {},
   "source": [
    "Create a split map with Earth Engine layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=(40, -100), zoom=4, height=600)\n",
    "\n",
    "nlcd_2001 = ee.Image(\"USGS/NLCD_RELEASES/2019_REL/NLCD/2001\").select(\"landcover\")\n",
    "nlcd_2019 = ee.Image(\"USGS/NLCD_RELEASES/2021_REL/NLCD/2021\").select(\"landcover\")\n",
    "\n",
    "left_layer = geemap.ee_tile_layer(nlcd_2001, {}, \"NLCD 2001\")\n",
    "right_layer = geemap.ee_tile_layer(nlcd_2019, {}, \"NLCD 2021\")\n",
    "\n",
    "m.split_map(left_layer, right_layer, left_label=\"NLCD 2001\", right_label=\"NLCD 2021\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73",
   "metadata": {},
   "source": [
    "### Linked maps\n",
    "\n",
    "Create a 2x2 linked map for visualizing Sentinel-2 imagery with different band combinations. Note that this feature does not work properly with Colab. Panning one map would not pan other maps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74",
   "metadata": {},
   "outputs": [],
   "source": [
    "image = (\n",
    "    ee.ImageCollection(\"COPERNICUS/S2\")\n",
    "    .filterDate(\"2018-09-01\", \"2018-09-30\")\n",
    "    .map(lambda img: img.divide(10000))\n",
    "    .median()\n",
    ")\n",
    "\n",
    "vis_params = [\n",
    "    {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "    {\"bands\": [\"B8\", \"B11\", \"B4\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "    {\"bands\": [\"B8\", \"B4\", \"B3\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "    {\"bands\": [\"B12\", \"B12\", \"B4\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "]\n",
    "\n",
    "labels = [\n",
    "    \"Natural Color (B4/B3/B2)\",\n",
    "    \"Land/Water (B8/B11/B4)\",\n",
    "    \"Color Infrared (B8/B4/B3)\",\n",
    "    \"Vegetation (B12/B11/B4)\",\n",
    "]\n",
    "\n",
    "geemap.linked_maps(\n",
    "    rows=2,\n",
    "    cols=2,\n",
    "    height=\"300px\",\n",
    "    center=[38.4151, 21.2712],\n",
    "    zoom=12,\n",
    "    ee_objects=[image],\n",
    "    vis_params=vis_params,\n",
    "    labels=labels,\n",
    "    label_position=\"topright\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75",
   "metadata": {},
   "source": [
    "### Timeseries inspector and time slider\n",
    "\n",
    "#### Timeseries inspector\n",
    "\n",
    "Check the available years of NLCD."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "collection = ee.ImageCollection(\"USGS/NLCD_RELEASES/2019_REL/NLCD\").select(\"landcover\")\n",
    "vis_params = {\"bands\": [\"landcover\"]}\n",
    "years = collection.aggregate_array(\"system:index\").getInfo()\n",
    "years"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77",
   "metadata": {},
   "source": [
    "Create a timeseries inspector for NLCD. Note that ipyleaflet has a bug with the SplitControl. You can't pan the map, which should be resolved in a future ipyleaflet release."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.ts_inspector(\n",
    "    left_ts=collection,\n",
    "    right_ts=collection,\n",
    "    left_names=years,\n",
    "    right_names=years,\n",
    "    left_vis=vis_params,\n",
    "    right_vis=vis_params,\n",
    "    width=\"80px\",\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79",
   "metadata": {},
   "source": [
    "#### Time slider\n",
    "\n",
    "Note that this feature may not work properly with in the Colab environment. Restart Colab runtime if the time slider does not work.\n",
    "\n",
    "Create a map for visualizing MODIS vegetation data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "\n",
    "collection = (\n",
    "    ee.ImageCollection(\"MODIS/MCD43A4_006_NDVI\")\n",
    "    .filter(ee.Filter.date(\"2018-06-01\", \"2018-07-01\"))\n",
    "    .select(\"NDVI\")\n",
    ")\n",
    "vis_params = {\n",
    "    \"min\": 0.0,\n",
    "    \"max\": 1.0,\n",
    "    \"palette\": \"ndvi\",\n",
    "}\n",
    "\n",
    "m.add_time_slider(collection, vis_params, time_interval=2)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81",
   "metadata": {},
   "source": [
    "Create a map for visualizing weather data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "\n",
    "collection = (\n",
    "    ee.ImageCollection(\"NOAA/GFS0P25\")\n",
    "    .filterDate(\"2018-12-22\", \"2018-12-23\")\n",
    "    .limit(24)\n",
    "    .select(\"temperature_2m_above_ground\")\n",
    ")\n",
    "\n",
    "vis_params = {\n",
    "    \"min\": -40.0,\n",
    "    \"max\": 35.0,\n",
    "    \"palette\": [\"blue\", \"purple\", \"cyan\", \"green\", \"yellow\", \"red\"],\n",
    "}\n",
    "\n",
    "labels = [str(n).zfill(2) + \":00\" for n in range(0, 24)]\n",
    "m.add_time_slider(collection, vis_params, labels=labels, time_interval=1, opacity=0.8)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83",
   "metadata": {},
   "source": [
    "Visualizing Sentinel-2 imagery"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[37.75, -122.45], zoom=12)\n",
    "\n",
    "collection = (\n",
    "    ee.ImageCollection(\"COPERNICUS/S2_SR\")\n",
    "    .filterBounds(ee.Geometry.Point([-122.45, 37.75]))\n",
    "    .filterMetadata(\"CLOUDY_PIXEL_PERCENTAGE\", \"less_than\", 10)\n",
    ")\n",
    "\n",
    "vis_params = {\"min\": 0, \"max\": 4000, \"bands\": [\"B8\", \"B4\", \"B3\"]}\n",
    "\n",
    "m.add_time_slider(collection, vis_params)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85",
   "metadata": {},
   "source": [
    "### Exercise 2 - Creating land cover maps with a legend\n",
    "\n",
    "Create a split map for visualizing NLCD land cover change in a selected US state between 2001 and 2019. Add the NLCD legend to the map. Relevant Earth Engine assets:\n",
    "\n",
    "-   [ee.FeatureCollection(\"TIGER/2018/States\")](https://developers.google.com/earth-engine/datasets/catalog/TIGER_2018_States)\n",
    "-   [ee.ImageCollection(\"USGS/NLCD_RELEASES/2019_REL/NLCD\")](https://developers.google.com/earth-engine/datasets/catalog/USGS_NLCD_RELEASES_2019_REL_NLCD)\n",
    "\n",
    "A sample map for visualizing NLCD land cover change in Texas is shown below:\n",
    "\n",
    "![](https://i.imgur.com/1b62CeI.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86",
   "metadata": {},
   "source": [
    "## Creating timelapse animations\n",
    "\n",
    "### MODIS vegetation indices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88",
   "metadata": {},
   "outputs": [],
   "source": [
    "roi = Map.user_roi\n",
    "if roi is None:\n",
    "    roi = ee.Geometry.BBox(-18.6983, -36.1630, 52.2293, 38.1446)\n",
    "    Map.addLayer(roi)\n",
    "    Map.centerObject(roi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89",
   "metadata": {},
   "outputs": [],
   "source": [
    "timelapse = geemap.modis_ndvi_timelapse(\n",
    "    roi,\n",
    "    out_gif=\"ndvi.gif\",\n",
    "    data=\"Terra\",\n",
    "    band=\"NDVI\",\n",
    "    start_date=\"2000-01-01\",\n",
    "    end_date=\"2022-12-31\",\n",
    "    frames_per_second=3,\n",
    "    title=\"MODIS NDVI Timelapse\",\n",
    "    overlay_data=\"countries\",\n",
    ")\n",
    "geemap.show_image(timelapse)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90",
   "metadata": {},
   "source": [
    "### MODIS temperature data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92",
   "metadata": {},
   "outputs": [],
   "source": [
    "roi = Map.user_roi\n",
    "if roi is None:\n",
    "    roi = ee.Geometry.BBox(-171.21, -57.13, 177.53, 79.99)\n",
    "    Map.addLayer(roi)\n",
    "    Map.centerObject(roi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93",
   "metadata": {},
   "outputs": [],
   "source": [
    "timelapse = geemap.modis_ocean_color_timelapse(\n",
    "    satellite=\"Aqua\",\n",
    "    start_date=\"2018-01-01\",\n",
    "    end_date=\"2020-12-31\",\n",
    "    roi=roi,\n",
    "    frequency=\"month\",\n",
    "    out_gif=\"temperature.gif\",\n",
    "    overlay_data=\"continents\",\n",
    "    overlay_color=\"yellow\",\n",
    "    overlay_opacity=0.5,\n",
    ")\n",
    "geemap.show_image(timelapse)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94",
   "metadata": {},
   "source": [
    "### GOES timelapse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95",
   "metadata": {},
   "outputs": [],
   "source": [
    "roi = ee.Geometry.BBox(167.1898, -28.5757, 202.6258, -12.4411)\n",
    "start_date = \"2022-01-15T03:00:00\"\n",
    "end_date = \"2022-01-15T07:00:00\"\n",
    "data = \"GOES-17\"\n",
    "scan = \"full_disk\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96",
   "metadata": {},
   "outputs": [],
   "source": [
    "timelapse = geemap.goes_timelapse(\n",
    "    roi, \"goes.gif\", start_date, end_date, data, scan, framesPerSecond=5\n",
    ")\n",
    "geemap.show_image(timelapse)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97",
   "metadata": {},
   "outputs": [],
   "source": [
    "roi = ee.Geometry.BBox(-159.5954, 24.5178, -114.2438, 60.4088)\n",
    "start_date = \"2021-10-24T14:00:00\"\n",
    "end_date = \"2021-10-25T01:00:00\"\n",
    "data = \"GOES-17\"\n",
    "scan = \"full_disk\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98",
   "metadata": {},
   "outputs": [],
   "source": [
    "timelapse = geemap.goes_timelapse(\n",
    "    roi, \"hurricane.gif\", start_date, end_date, data, scan, framesPerSecond=5\n",
    ")\n",
    "geemap.show_image(timelapse)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99",
   "metadata": {},
   "outputs": [],
   "source": [
    "roi = ee.Geometry.BBox(-121.0034, 36.8488, -117.9052, 39.0490)\n",
    "start_date = \"2020-09-05T15:00:00\"\n",
    "end_date = \"2020-09-06T02:00:00\"\n",
    "data = \"GOES-17\"\n",
    "scan = \"full_disk\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "100",
   "metadata": {},
   "outputs": [],
   "source": [
    "timelapse = geemap.goes_fire_timelapse(\n",
    "    roi, \"fire.gif\", start_date, end_date, data, scan, framesPerSecond=5\n",
    ")\n",
    "geemap.show_image(timelapse)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "101",
   "metadata": {},
   "source": [
    "### Exercise - Creating timelapse animations\n",
    "\n",
    "Use the geemap timelapse GUI to create a timelapse animation for any location of your choice. Share the timelapse on social media and use the hashtag such as #EarthEngine and #geemap. See [this](https://i.imgur.com/YaCHvKC.gif) example.\n",
    "\n",
    "![](https://i.imgur.com/ohrXeFC.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "102",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "m.add_gui(\"timelapse\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "103",
   "metadata": {},
   "source": [
    "## Drought monitoring\n",
    "\n",
    "In this section, we will explore drought datasets and anylyze drought patterns using Google Earth Engine. There are different [types of droughts](https://drought.unl.edu/Education/DroughtIn-depth/TypesofDrought.aspx), including meteorological drought, agricultural drought, hydrological drought, and socioeconomic drought. Droughts can be monitored using various drought indices, such as the Palmer Drought Severity Index (PDSI), Standardized Precipitation Index (SPI), and Standardized Precipitation Evapotranspiration Index (SPEI).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "104",
   "metadata": {},
   "source": [
    "### Exploring drought datasets\n",
    "\n",
    "There are several drought datasets available in the [Earth Engine Community Catalog](https://gee-community-catalog.org), including:\n",
    "\n",
    "- [United States Drought Monitor](https://gee-community-catalog.org/projects/usdm)\n",
    "- [North American Drought Monitor (NADM)](https://gee-community-catalog.org/projects/nadm)\n",
    "- [Canadian Drought Outlook](https://gee-community-catalog.org/projects/can_drought_outlook)\n",
    "- [United States Seasonal Drought Outlook](https://gee-community-catalog.org/projects/ussdo)\n",
    "\n",
    "The [Earth Engine Public Data Catalog](https://developers.google.com/earth-engine/datasets/catalog) also hosts several [drought datasets](https://developers.google.com/earth-engine/datasets/tags/drought), including:\n",
    "\n",
    "- [GRIDMET DROUGHT: CONUS Drought Indices](https://developers.google.com/earth-engine/datasets/catalog/GRIDMET_DROUGHT)\n",
    "- [SPEIbase: Standardised Precipitation-Evapotranspiration Index database](https://developers.google.com/earth-engine/datasets/catalog/CSIC_SPEI_2_9)\n",
    "- [KBDI: Keetch-Byram Drought Index](https://developers.google.com/earth-engine/datasets/catalog/UTOKYO_WTLAB_KBDI_v1)\n",
    "\n",
    "Let's explore the USDM dataset in the Earth Engine Community Catalog.\n",
    "\n",
    "The U.S. Drought Monitor is a map released every Thursday, showing parts of the U.S. that are in drought. The map uses five classifications: abnormally dry (D0), showing areas that may be going into or are coming out of drought, and four levels of drought: moderate (D1), severe (D2), extreme (D3) and exceptional (D4).\n",
    "\n",
    "The Drought Monitor has been a team effort since its inception in 1999, produced jointly by the National Drought Mitigation Center (NDMC) at the University of Nebraska-Lincoln, the National Oceanic and Atmospheric Administration (NOAA), and the U.S. Department of Agriculture (USDA). The NDMC hosts the web site of the drought monitor and the associated data, and provides the map and data to NOAA, USDA and other agencies. It is freely available at https://droughtmonitor.unl.edu.\n",
    "\n",
    "![](https://i.imgur.com/Y2cOxiX.png)\n",
    "\n",
    "To visualize the USDM data, open the [USDM Explorer Web App](https://sat-io.earthengine.app/view/usdm-explorer) and select any US county to view the weekly USDM data for that county.\n",
    "\n",
    "![](https://i.imgur.com/kLTVbnl.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "105",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "collection = ee.ImageCollection(\"projects/sat-io/open-datasets/us-drought-monitor\")\n",
    "images = collection.filterDate(\"2023-01-01\", \"2024-01-01\")\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4,\n",
    "    \"palette\": [\"#FFFF00\", \"#FCD37F\", \"#FFAA00\", \"#E60000\", \"#730000\"],\n",
    "}\n",
    "m.add_layer(images.first(), vis_params, \"US Drought Monitor\")\n",
    "legend_dict = {\n",
    "    \"D0-Abnormally dry\": \"#FFFF00\",\n",
    "    \"D1-Moderate drought\": \"#FCD37F\",\n",
    "    \"D2-Severe drought\": \"#FFAA00\",\n",
    "    \"D3-Extreme drought\": \"#E60000\",\n",
    "    \"D4-Exceptional drought\": \"#730000\",\n",
    "}\n",
    "m.add_legend(title=\"Drought Severity\", legend_dict=legend_dict)\n",
    "\n",
    "CONUS = ee.Geometry.BBox(-126.2109, 23.3221, -66.3574, 50.1206)\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\").filterBounds(CONUS)\n",
    "counties = ee.FeatureCollection(\"TIGER/2018/Counties\").filterBounds(CONUS)\n",
    "style = {\"color\": \"000000ff\", \"width\": 2, \"lineType\": \"solid\", \"fillColor\": \"00000000\"}\n",
    "m.add_layer(states.style(**style), {}, \"US States\")\n",
    "m.add_layer(counties, {}, \"US Counties\", False)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "106",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/48ofcys.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "107",
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_time_slider(images, vis_params, time_interval=1, loop=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "108",
   "metadata": {},
   "source": [
    "### Creating drought timeseries animations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "109",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_gif = \"us_drought_monitor.gif\"\n",
    "geemap.create_timelapse(\n",
    "    images,\n",
    "    \"2023-06-01\",\n",
    "    \"2024-01-01\",\n",
    "    region=CONUS,\n",
    "    frequency=\"day\",\n",
    "    vis_params=vis_params,\n",
    "    overlay_data=\"us_states\",\n",
    "    overlay_color=\"white\",\n",
    "    out_gif=out_gif,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "110",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.show_image(out_gif)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "111",
   "metadata": {},
   "source": [
    "### Analyzing drought datasets\n",
    "\n",
    "NASA reported [July 2023 as Hottest Month on Record Ever Since 1880](https://www.nasa.gov/news-release/nasa-clocks-july-2023-as-hottest-month-on-record-ever-since-1880)\n",
    "\n",
    "![](https://www.nasa.gov/wp-content/uploads/2023/08/microsoftteams-image_26.png)\n",
    "\n",
    "In this section, we will analyze drought patterns in the United States using the 4-km Gridded Surface Meteorological ([GRIDMET](https://developers.google.com/earth-engine/datasets/catalog/GRIDMET_DROUGHT)) dataset, which contains drought indices such as the standardized precipitation index (SPI), the evaporative drought demand index (EDDI), the standardized precipitation evapotranspiration index (SPEI), the Palmer Drought Severity Index (PDSI) and Palmer Z Index (Z). The GRIDMET dataset is available from 1980 to the present. The dataset is updated every 5 days and has a spatial resolution of 4 km.\n",
    "\n",
    "Let's filter the GRIDMET dataset to the year of 2023 and visualize the PDSI index for the month of July 2023."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "112",
   "metadata": {},
   "outputs": [],
   "source": [
    "start_date = \"2023-07-01\"\n",
    "end_date = \"2023-08-01\"\n",
    "pdsi_col = ee.ImageCollection(\"GRIDMET/DROUGHT\").filterDate(start_date, end_date)\n",
    "pdsi_col"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "113",
   "metadata": {},
   "source": [
    "Print out the GRIDMET dataset ids, which contain the date information in the `YYYYMMDD` format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "114",
   "metadata": {},
   "outputs": [],
   "source": [
    "pdsi_col.aggregate_array(\"system:id\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "115",
   "metadata": {},
   "source": [
    "Create a mean GRIDMET image for the month of July 2023."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "116",
   "metadata": {},
   "outputs": [],
   "source": [
    "pdsi_image = pdsi_col.filterDate(start_date, end_date).mean()\n",
    "pdsi_image"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "117",
   "metadata": {},
   "source": [
    "Visualize the GRIDMET dataset for the month of July 2023."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "118",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "\n",
    "# Make color options for standardized variables spi/spei/eddi\n",
    "spi_vis = {\"min\": -2.5, \"max\": 2.5, \"palette\": \"jet_r\"}\n",
    "# Make color options for Palmer variables psdi/z\n",
    "drought_vis = {\"min\": -6, \"max\": 6, \"palette\": \"coolwarm_r\"}\n",
    "\n",
    "pdsi = pdsi_image.select(\"pdsi\")\n",
    "z = pdsi_image.select(\"z\")\n",
    "spi30d = pdsi_image.select(\"spi30d\")\n",
    "spi90d = pdsi_image.select(\"spi90d\")\n",
    "spi180d = pdsi_image.select(\"spi180d\")\n",
    "spi1y = pdsi_image.select(\"spi1y\")\n",
    "m.add_layer(spi30d, spi_vis, \"SPI-30d\")\n",
    "m.add_layer(spi90d, spi_vis, \"SPI-90d\")\n",
    "m.add_layer(spi180d, spi_vis, \"SPI-180d\")\n",
    "m.add_layer(spi1y, spi_vis, \"SPI-1y\")\n",
    "m.add_layer(z, drought_vis, \"Z-Index\")\n",
    "m.add_layer(pdsi, drought_vis, \"PDSI\")\n",
    "m.add_colorbar(drought_vis, label=\"Drought Index\")\n",
    "m.add_colorbar(spi_vis, label=\"SPI Index\")\n",
    "\n",
    "CONUS = ee.Geometry.BBox(-126.2109, 23.3221, -66.3574, 50.1206)\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\").filterBounds(CONUS)\n",
    "counties = ee.FeatureCollection(\"TIGER/2018/Counties\").filterBounds(CONUS)\n",
    "style = {\"color\": \"000000ff\", \"width\": 2, \"lineType\": \"solid\", \"fillColor\": \"00000000\"}\n",
    "m.add_layer(states.style(**style), {}, \"US States\")\n",
    "m.add_layer(counties, {}, \"US Counties\", False)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "119",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/kQwzcW7.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "120",
   "metadata": {},
   "source": [
    "You can compare the GRIDMET PDSI map for July 2023 with the map of [historical Palmer Drought Severity Index](https://www.ncei.noaa.gov/access/monitoring/historical-palmers/maps/psi/202307) (PDSI) from NECI.\n",
    "\n",
    "![](https://www.ncei.noaa.gov/monitoring-content/sotc/drought/psi/psi-202307.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "121",
   "metadata": {},
   "source": [
    "Let's select a county in the United States and extract the historical PDSI and SPI values. You can place a marker on the map to select a county. If no county is selected, the default county is set to the Clark County, Nevada, which includes the city of Las Vegas. We will extract the PDSI and SPI values for the selected county and create a time series chart."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "122",
   "metadata": {},
   "outputs": [],
   "source": [
    "if m.user_roi is not None:\n",
    "    point = m.user_rois\n",
    "else:\n",
    "    point = ee.Geometry.Point(-115.04, 36.15)\n",
    "\n",
    "roi = counties.filterBounds(point)\n",
    "pdsi_col = (\n",
    "    ee.ImageCollection(\"GRIDMET/DROUGHT\")\n",
    "    .select(\"pdsi\")\n",
    "    .map(lambda img: img.clipToCollection(roi))\n",
    ")\n",
    "spi_col = (\n",
    "    ee.ImageCollection(\"GRIDMET/DROUGHT\")\n",
    "    .select(\"spi30d\")\n",
    "    .map(lambda img: img.clipToCollection(roi))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "123",
   "metadata": {},
   "source": [
    "Create a monthly time series of PDSI for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "124",
   "metadata": {},
   "outputs": [],
   "source": [
    "pdsi_ts = geemap.create_timeseries(\n",
    "    pdsi_col,\n",
    "    start_date=\"1980-01-01\",\n",
    "    end_date=\"2024-07-01\",\n",
    "    frequency=\"month\",\n",
    "    reducer=\"mean\",\n",
    ")\n",
    "pdsi_ts"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "125",
   "metadata": {},
   "source": [
    "Create a monthly time series of SPI for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "126",
   "metadata": {},
   "outputs": [],
   "source": [
    "spi_ts = geemap.create_timeseries(\n",
    "    spi_col,\n",
    "    start_date=\"1980-01-01\",\n",
    "    end_date=\"2024-07-01\",\n",
    "    frequency=\"month\",\n",
    "    reducer=\"mean\",\n",
    ")\n",
    "spi_ts"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "127",
   "metadata": {},
   "source": [
    "Note that both the PDSI and SPI time series have 534 images, which represent the monthly values from January 1980 to June 2024. Let's select the month of March 2021 and visualize the PDSI and SPI values for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "128",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map()\n",
    "start_date = \"2021-03-01\"\n",
    "end_date = \"2021-04-01\"\n",
    "pdsi_image = pdsi_col.filterDate(start_date, end_date).first()\n",
    "spi_image = spi_col.filterDate(start_date, end_date).first()\n",
    "m.add_layer(spi_image, drought_vis, \"SPI\")\n",
    "m.add_layer(pdsi_image, drought_vis, \"PDSI\")\n",
    "m.centerObject(roi, 8)\n",
    "m.add_colorbar(drought_vis, label=\"Drought Index\", layer_name=\"PDSI\")\n",
    "m.add_colorbar(spi_vis, label=\"SPI Index\", layer_name=\"SPI\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "129",
   "metadata": {},
   "source": [
    "Calculate the monthly mean PDSI for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "130",
   "metadata": {},
   "outputs": [],
   "source": [
    "pdsi_csv = \"pdsi_stats.csv\"\n",
    "geemap.zonal_stats(pdsi_ts, roi, pdsi_csv, stat_type=\"MEAN\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "131",
   "metadata": {},
   "source": [
    "Calculate the monthly mean SPI for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "132",
   "metadata": {},
   "outputs": [],
   "source": [
    "spi_csv = \"spi_stats.csv\"\n",
    "geemap.zonal_stats(spi_ts, roi, spi_csv, stat_type=\"MEAN\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "133",
   "metadata": {},
   "source": [
    "Read the PDSI values from the output csv and transform the data to a pandas DataFrame with a `pdsi` column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "134",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = geemap.csv_to_df(pdsi_csv)\n",
    "pdsi_columns = [col for col in df.columns if \"pdsi\" in col.lower()]\n",
    "df_pdsi = df[pdsi_columns]\n",
    "df_pdsi = df_pdsi.T\n",
    "df_pdsi.columns = [\"pdsi\"]\n",
    "df_pdsi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "135",
   "metadata": {},
   "source": [
    "Read the SPI values from the output csv and transform the data to a pandas DataFrame with a `spi` column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "136",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = geemap.csv_to_df(spi_csv)\n",
    "spi_columns = [col for col in df.columns if \"spi\" in col.lower()]\n",
    "df_spi = df[spi_columns]\n",
    "df_spi = df_spi.T\n",
    "df_spi.columns = [\"spi\"]\n",
    "df_spi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "137",
   "metadata": {},
   "source": [
    "Combine the PDSI and SPI data into a single DataFrame with `pdsi`, `spi`, and `date` columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "138",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_pdsi[\"spi\"] = df_spi[\"spi\"].tolist()\n",
    "dates = geemap.image_dates(pdsi_ts).getInfo()\n",
    "df_pdsi[\"date\"] = dates\n",
    "df_pdsi.columns = [\"pdsi\", \"spi\", \"date\"]\n",
    "df_pdsi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "139",
   "metadata": {},
   "source": [
    "Create a bar chart for showing the historical PDSI values for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "140",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.bar_chart(df_pdsi, x=\"date\", y=[\"pdsi\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "141",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/2pXuzTk.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "142",
   "metadata": {},
   "source": [
    "Create a bar chart for showing the historical SPI values for the selected county."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "143",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.bar_chart(df_pdsi, x=\"date\", y=[\"spi\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "144",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/NyzyD73.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "145",
   "metadata": {},
   "source": [
    "Show the combined PDSI and SPI values in a single chart."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "146",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.bar_chart(df_pdsi, x=\"date\", y=[\"pdsi\", \"spi\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "147",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/2FrZGKd.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "148",
   "metadata": {},
   "source": [
    "### Exercise - Analyzing drought data for a selected county\n",
    "\n",
    "Select a county in the United States and extract the historical PDSI values. Create a time series chart to visualize the PDSI values for the selected county."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "149",
   "metadata": {},
   "source": [
    "## Analyzing and visualizing precipitation data\n",
    "\n",
    "### Exploring precipitation datasets\n",
    "\n",
    "The Earth Engine Public Data Catalog hosts a lot of [precipitation datasets](https://developers.google.com/earth-engine/datasets/tags/precipitation), including:\n",
    "\n",
    "- [SPEIbase: Standardised Precipitation-Evapotranspiration Index database](https://developers.google.com/earth-engine/datasets/catalog/CSIC_SPEI_2_9)\n",
    "- [ERA5-Land Hourly - ECMWF Climate Reanalysis](https://developers.google.com/earth-engine/datasets/catalog/ECMWF_ERA5_LAND_HOURLY)\n",
    "- [GPM: Monthly Global Precipitation Measurement](https://developers.google.com/earth-engine/datasets/catalog/NASA_GPM_L3_IMERG_MONTHLY_V07)\n",
    "- [Daymet V4: Daily Surface Weather and Climatological Summaries](https://developers.google.com/earth-engine/datasets/catalog/NASA_ORNL_DAYMET_V4)\n",
    "- [PRISM Daily Spatial Climate Dataset AN81d](https://developers.google.com/earth-engine/datasets/catalog/OREGONSTATE_PRISM_AN81d)\n",
    "- [TRMM 3B42: 3-Hourly Precipitation Estimates](https://developers.google.com/earth-engine/datasets/catalog/TRMM_3B42)\n",
    "- [CHIRPS Daily: Climate Hazards Group InfraRed Precipitation With Station Data](https://developers.google.com/earth-engine/datasets/catalog/UCSB-CHG_CHIRPS_DAILY)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "150",
   "metadata": {},
   "source": [
    "### Calculating Standardized Precipitation Index (SPI)\n",
    "\n",
    "The [Standardized Precipitation Index (SPI)](https://climatedataguide.ucar.edu/climate-data/standardized-precipitation-index-spi) is a widely used index to characterize meteorological drought on a range of timescales. On short timescales, the SPI is closely related to soil moisture, while at longer timescales, the SPI can be related to groundwater and reservoir storage. The SPI can be compared across regions with markedly different climates. It quantifies observed precipitation as a standardized departure from a selected probability distribution function that models the raw precipitation data. The raw precipitation data are typically fitted to a gamma or a Pearson Type III distribution, and then transformed to a normal distribution. The SPI values can be interpreted as the number of standard deviations by which the observed anomaly deviates from the long-term mean. The SPI can be created for differing periods of 1-to-36 months, using monthly input data. \n",
    "\n",
    "The SPI is calculated as follows:\n",
    "\n",
    "`SPI = (P-P*) /  σp`\n",
    "\n",
    "where P = precipitation, p* = mean precipitation, and σp = standard deviation of precipitation.\n",
    "\n",
    "In this section, we will use the [PRISM Daily Spatial Climate Dataset](https://developers.google.com/earth-engine/datasets/catalog/OREGONSTATE_PRISM_AN81d) to calculate the SPI. It has daily precipitation data from 1981 to present with a spatial resolution of 4 km. The dataset is based on the Parameter-elevation Regressions on Independent Slopes Model (PRISM) and is available from the [Oregon State University PRISM Climate Group](http://prism.oregonstate.edu).\n",
    "\n",
    "Let's filter the PRISM dataset to the month of July 2023 and calculate the total precipitation for the month."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "151",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "dataset = (\n",
    "    ee.ImageCollection(\"OREGONSTATE/PRISM/AN81d\")\n",
    "    .filter(ee.Filter.date(\"2023-07-01\", \"2023-08-01\"))\n",
    "    .select(\"ppt\")\n",
    ")\n",
    "ppt = dataset.sum()\n",
    "\n",
    "ppt_vis = {\n",
    "    \"min\": 0.0,\n",
    "    \"max\": 200.0,\n",
    "    \"palette\": [\"red\", \"yellow\", \"green\", \"cyan\", \"purple\"],\n",
    "}\n",
    "\n",
    "CONUS = ee.Geometry.BBox(-126.2109, 23.3221, -66.3574, 50.1206)\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\").filterBounds(CONUS)\n",
    "counties = ee.FeatureCollection(\"TIGER/2018/Counties\").filterBounds(CONUS)\n",
    "style = {\"color\": \"000000ff\", \"width\": 2, \"lineType\": \"solid\", \"fillColor\": \"00000000\"}\n",
    "m.add_layer(ppt, ppt_vis, \"Precipitation\")\n",
    "m.add_layer(states.style(**style), {}, \"US States\")\n",
    "m.add_layer(counties, {}, \"US Counties\", False)\n",
    "m.add_colorbar(ppt_vis, label=\"Precipitation (mm)\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "152",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/8YxbNTI.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "153",
   "metadata": {},
   "source": [
    "Create monthly precipitation images from 1981 to 2024."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "154",
   "metadata": {},
   "outputs": [],
   "source": [
    "if m.user_roi is not None:\n",
    "    point = m.user_rois\n",
    "else:\n",
    "    point = ee.Geometry.Point(-115.04, 36.15)\n",
    "\n",
    "roi = counties.filterBounds(point)\n",
    "\n",
    "dataset = ee.ImageCollection(\"OREGONSTATE/PRISM/AN81d\").select(\"ppt\")\n",
    "prism_ts = geemap.create_timeseries(\n",
    "    dataset, \"1981-01-01\", \"2024-07-01\", frequency=\"month\", reducer=\"sum\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "155",
   "metadata": {},
   "source": [
    "Calculate the long-term mean precipitation and standard deviation of precipitation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "156",
   "metadata": {},
   "outputs": [],
   "source": [
    "prism_ts_image = prism_ts.toBands()\n",
    "ppt_mean = prism_ts_image.reduce(ee.Reducer.mean())\n",
    "ppt_std = prism_ts_image.reduce(ee.Reducer.stdDev())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "157",
   "metadata": {},
   "source": [
    "Calculate the SPI for the month of July 2023."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "158",
   "metadata": {},
   "outputs": [],
   "source": [
    "ppt_202307 = prism_ts.filterDate(\"2023-07-01\", \"2023-08-01\").first()\n",
    "spi_202307 = ppt_202307.subtract(ppt_mean).divide(ppt_std)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "159",
   "metadata": {},
   "source": [
    "Visualize the SPI for the month of July 2023."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "160",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = geemap.Map(center=[40, -100], zoom=4)\n",
    "spi_vis = {\"min\": -2.5, \"max\": 2.5, \"palette\": \"jet_r\"}\n",
    "m.add_layer(spi_202307, spi_vis, \"SPI\")\n",
    "m.add_layer(states.style(**style), {}, \"US States\")\n",
    "m.add_layer(counties, {}, \"US Counties\", False)\n",
    "m.add_colorbar(spi_vis, label=\"SPI\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "161",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/4AKrk4z.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "162",
   "metadata": {},
   "source": [
    "### Exercise - Calculating SPI for a selected region\n",
    "\n",
    "Select a region in the United States and calculate the SPI for the region using the PRISM dataset. Visualize the SPI for the region."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
